﻿/****************************************************************
*   作者：Morain
*   创建时间：2018/2/10 22:46:49
*   描述说明：
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ETSModel
{
  /// <summary>
  /// 连接类型
  /// </summary>
  public enum ChannelType
  {
    /// <summary>
    /// 连接
    /// </summary>
    Connect,
    /// <summary>
    /// 监听
    /// </summary>
    Accept
  }

  /// <summary>
  /// 一个连接通道
  /// </summary>
  public abstract class AChannel : IDisposable
  {
    public long Id { get; set; }

    public ChannelType ChannelType { get; }

    protected AService service;

    public IPEndPoint RemoteAddress { get; protected set; }

    private event Action<AChannel, SocketError> errorCallback;

    public event Action<AChannel, SocketError> ErrorCallback
    {
      add
      {
        errorCallback += value;
      }
      remove
      {
        errorCallback -= value;
      }
    }

    protected void OnError(AChannel channel, SocketError e)
    {
      this.errorCallback?.Invoke(channel, e);
    }

    protected AChannel(AService service, ChannelType channelType)
    {
      this.Id = IdGenerater.GeneraterId();
      this.service = service;
      this.ChannelType = ChannelType;
    }

    public abstract void Send(byte[] buffer);
    public abstract void Send(List<byte[]> buffers);

    public abstract Task<Packet> Recv();

    public virtual void Dispose()
    {
      if (this.Id == 0) return;

      long id = this.Id;
      this.Id = 0;
      this.service.Remove(id);
    }
  }
}
